# Copyright (c) 2022, hzmes and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc
from six import string_types
from frappe.utils import cint, cstr, flt
# 导入sync_to_k3cloud_plan_of_answer
from srm.srm.doctype.srm_server_config.srm_server_config import sync_to_k3cloud_plan_of_answer

class SRMSupplyPlanOfSupplier(Document):
	@frappe.whitelist()
	def sync_to_erp_answerdetail(self):
		entry_list = []
		for i in self.orderitem:
			ls = []
			if i.answer_info:
				l = i.answer_info.split(",")
				for item in l:
					ls = item.split("/")
					ls.append(i.po_entryid)
					entry_list.append(ls)
		if len(entry_list)>0:
			r = sync_to_k3cloud_plan_of_answer(entry_list)
			return r
		else:
			frappe.throw("请确认答交记录是否有效!")

	@frappe.whitelist()
	def query_sum_assignqty(self, material_number):
		sql = f"""select i1.need_date, sum(i1.assign_qty) as assign_qty from `tabSRM Supply Plan Of Supplier OrderItem` i1 where i1.parent = '{self.name}' and i1.material_number = '{material_number}' group by i1.need_date;"""
		result = frappe.db.sql(sql, as_dict=1)
		if result:
			return result
	
	# 送货单事后修复交期回复表中的relation_qty
	@frappe.whitelist()
	def sync_relation_qty(self):
		# relation_qty
		sql_relation_qty = f"select t1.name as fbillno_name, t2.name as row_name, t2.relation_qty, IFNULL(t3.real_qty, 0) as real_qty from `tabSRM Supply Plan Of Supplier` t1 join `tabSRM Supply Plan Of Supplier OrderItem` t2 on t1.name = t2.parent and t1.is_last = 1 left join (select source_billname, sum(IFNULL(real_qty, 0)) as real_qty from `tabSRM Purchase Delivery Sub` where IFNULL(real_qty, 0)>0 and creation > adddate(now(), interval -14 day) group by source_billname) t3 on t2.name = t3.source_billname where 1=1 and t1.name = '{self.name}';"
		r_relation_qty = frappe.db.sql(sql_relation_qty, as_dict = 1)
		for item in r_relation_qty:
			if flt(item.real_qty) != flt(item.relation_qty):
				frappe.db.set_value('SRM Supply Plan Of Supplier OrderItem', item.row_name, {"relation_qty": item.real_qty})
		# delivery_qty, 多一个条件: and docstatus = 1
		sql_delivery_qty = f"select t1.name as fbillno_name, t2.name as row_name, t2.relation_qty, IFNULL(t3.real_qty, 0) as real_qty from `tabSRM Supply Plan Of Supplier` t1 join `tabSRM Supply Plan Of Supplier OrderItem` t2 on t1.name = t2.parent and t1.is_last = 1 left join (select source_billname, sum(IFNULL(real_qty, 0)) as real_qty from `tabSRM Purchase Delivery Sub` where IFNULL(real_qty, 0)>0 and creation > adddate(now(), interval -14 day) and docstatus = 1 group by source_billname) t3 on t2.name = t3.source_billname where 1=1 and t1.name = '{self.name}';"
		r_delivery_qty = frappe.db.sql(sql_relation_qty, as_dict = 1)
		for item in r_delivery_qty:
			if flt(item.real_qty) != flt(item.delivery_qty):
				frappe.db.set_value('SRM Supply Plan Of Supplier OrderItem', item.row_name, {"delivery_qty": item.real_qty})


	# 临时指定MPQ
	@frappe.whitelist()
	def update_mpq(self, material_number, mpq):
		for i in self.orderitem:
			if i.material_number == material_number:
				i.mpq = mpq if mpq>1 else 1
		self.save(ignore_permissions=True)
		self.reload()


# 从交期回复中生成送货单
@frappe.whitelist()
def make_purchase_delivery_from_plan(source_name, target_doc=None, args=None):
	# if args is None:
	# 	args = {}

	# if isinstance(args, string_types):
	# 	args = json.loads(args)

	# def select_item(d):
	# 	filtered_items = args.get("filtered_children", [])
	# 	child_filter = d.name in filtered_items if filtered_items else True

	def update_item(obj, target, source_parent):
		target.source_billtype = 'SRM Supply Plan Of Supplier'

	doc = get_mapped_doc(
		"SRM Supply Plan Of Supplier",
		source_name,
		{
			"SRM Supply Plan Of Supplier": {
				"doctype": "SRM Purchase Delivery",
				"field_map": {"name": "from_purchase_order"},
				"validation": {
					# "docstatus": ["=", 1],
					# "doc_closed": ["=", 'A'],
				},
			},
			"SRM Supply Plan Of Supplier OrderItem": {
				"doctype": "SRM Purchase Delivery Sub",
				"field_map": {
					"material_number": "material_number",
					"material_name": "material_name",
					"name": "source_billname",
					"po_entryid": "po_entryid",
					"answer_qty": "qty",
				},
				"postprocess": update_item,
				# 必须是采购员确认的行记录
				# "condition": select_item,		
			},
		},
		target_doc,
		ignore_permissions=True,
	)

	return doc


# 标准列表查询时，不同角色强行限制查询条件
def get_permission_query_conditions(user):
	purchase_person = frappe.get_doc('User', user).full_name
	roles = []
	for r in frappe.get_doc('User', user).roles:
		roles.append(r.role)
	# frappe.msgprint(roles)
	if ('System Manager' in roles):
		return ""
	elif ('SRM Supplier' in roles):
		return ""
	elif ('SRM Purchase Manager' in roles):
		return ""
	elif ('SRM Purchase' in roles):
		return f"""(`tabSRM Supply Plan Of Supplier`.buyer in ('{purchase_person}'))"""